package com.example.evan.devicereport;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i("Msg", msg.obj.toString());
            String[] strArr = msg.obj.toString().split(";");
            if (strArr.length == 3) {
                ((EditText) findViewById(R.id.result)).setText("返回值:" + strArr[0]);
                ((EditText) findViewById(R.id.fileLoc)).setText("存储路径:" + strArr[1]);
                ((EditText) findViewById(R.id.timeUsed)).setText("花费时间:" + strArr[2]);
            }
            ((Button) findViewById(R.id.btnStart)).setEnabled(true);
        }
    };

    private boolean mRunning = false;

    private Button bStart;
    private Button bStop;

    private long curDate;

    public String getIpAddr() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ip = wifiInfo.getIpAddress();

        String ipString = String.format(
                "%d.%d.%d.%d",
                (ip & 0xff),
                (ip >> 8 & 0xff),
                (ip >> 16 & 0xff),
                (ip >> 24 & 0xff));

        return ipString;
    }

    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            //Log.e("WifiPreference IpAddress", ex.toString());
        }
        return null;
    }

    public static String getHostIP() {

        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            Log.i("yao", "SocketException");
            e.printStackTrace();
        }
        return hostIp;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                //申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        8);
            }
        }
        //getActionBar().setTitle("Kevin's 测试程序");
//       FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });
        //Get device information
        EditText device = (EditText) findViewById(R.id.deviceId);
        EditText serial = (EditText) findViewById(R.id.deviceSerial);
        final EditText result = (EditText) findViewById(R.id.result);
        //Disable edit
//        device.setEnabled(false);
//        serial.setEnabled(false);
        device.setText(getIMEI(this.getBaseContext()));

        String ipAddr = getHostIP();

        if (ipAddr.length() > 8) {
            serial.setText(ipAddr);
        }
//        result.setHorizontallyScrolling(false);
//        result.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);

        bStart = (Button) findViewById(R.id.btnStart);
        //bStop = (Button) findViewById(R.id.btnStop);

        bStart.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //if (mHandler == null) {
                //mRunning = true;
                //mHandler = new Handler(thread.getLooper()) {
                //mHandler.post(mBackgroundRunnable);
                result.setText("发送开始..........");
                ((EditText) findViewById(R.id.fileLoc)).setText("");
                ((EditText) findViewById(R.id.timeUsed)).setText("");
                curDate = System.currentTimeMillis();
                new Thread(new MyThread()).start();
                //String strSend = onSendJson("");
                bStart.setEnabled(false);
                //}
            }
        });

//        bStop.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                mRunning = false;
//                result.setText("Stopped!!");
//            }
//        });
    }

    public class MyThread implements Runnable {
        @Override
        public void run() {
            //while (mRunning) {
            Log.i("Main", "thread running!");
            try {
                onSendJson("");
                //Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //}
        }
    }

//    Runnable mBackgroundRunnable = new Runnable() {
//        @Override
//        public void run() {
//            while(mRunning){
//                Log.i("Main", "thread running!");
//                try {
//                    onSendJson("");
//                    Thread.sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    };


    public static String createRandom(boolean numberFlag, int length) {
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }

    public List<String> getExtSDCardPath() {
        List<String> lResult = new ArrayList<String>();
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains("extSdCard")) {
                    String[] arr = line.split(" ");
                    String path = arr[1];
                    File file = new File(path);
                    if (file.isDirectory()) {
                        lResult.add(path);
                    }
                }
            }
            isr.close();
        } catch (Exception e) {
        }
        return lResult;
    }

    private String onSendJson(String Ip) {
        String strResult = "";
        final String urlPath = "http://123.57.155.162:8089/handler/TestHandler.ashx?param=send";
        URL url;
        try {
            url = new URL(urlPath);
            /*封装子对象*/
            JSONObject deviceInfo = new JSONObject();
            deviceInfo.put("device", ((EditText) findViewById(R.id.deviceId)).getText().toString());
            deviceInfo.put("data", "This is from android device send!! " + createRandom(true, 6));

            //String content = String.valueOf(deviceInfo);
            String content = "device=" + ((EditText) findViewById(R.id.deviceId)).getText().toString();
            content += "&data=IP: " + ((EditText) findViewById(R.id.deviceSerial)).getText().toString() + " " + createRandom(true, 6);
            Log.i("Raw send:  ", content);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setDoOutput(true);//设置允许输出
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            //conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Length", String
                    .valueOf(content.length()));
            OutputStream os = conn.getOutputStream();
            os.write(content.getBytes());
            os.close();
            /*服务器返回的响应码*/
            int code = conn.getResponseCode();

            if (code == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String retData = null;
                String responseData = "";
                while ((retData = in.readLine()) != null) {
                    responseData += retData;
                }
                in.close();
                JSONObject jsonObject = new JSONObject(responseData);
                //Save to file

                boolean isMounted = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
                File file = null;
                if (isMounted) {

                    File parent_path = Environment.getExternalStorageDirectory();

                    // 可以建立一个子目录专门存放自己专属文件
                    File dir = new File(parent_path.getAbsolutePath(), "kaiven");
                    dir.mkdir();

                    file = new File(dir.getAbsolutePath(), createRandom(false, 4) + ".txt");
                    if (!file.exists()) {
                        //create
                        try {
                            FileOutputStream outputStream = new FileOutputStream(file);
                            outputStream.write(responseData.getBytes());
                            outputStream.flush();
                            outputStream.close();

                        } catch (IOException e) {

                        }
                    }
                } else {
                    Log.i("SDCard错误", "未安装SDCard！");
                }


                String savedPath = "";
                if (file != null) {
                    savedPath = file.getPath();
                }

                //update
                long lDiff = System.currentTimeMillis() - curDate;
                strResult = jsonObject.getString("Result") + ";" + savedPath;
                //Use time: 379 ms
                strResult += ";" + String.valueOf(lDiff) + " ms";
                Message msg = Message.obtain();
                msg.obj = strResult;
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        } catch (Exception e) {
            Log.i("Error Exception", e.getMessage());
        }

        return strResult;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁线程
        //mHandler.removeCallbacks(mBackgroundRunnable);
    }


    public static String getIMEI(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        String strImei = telephonyManager.getDeviceId();

        return strImei;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent settingsIntent = new Intent(this, SettingsActivity.class);
            startActivity(settingsIntent);
            //return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
